package postionvalidator

import (
	"fmt"
	"time"
	"yunj/pkg/global"
	"yunj/pkg/yunj/app/enum/stateenum"
	"yunj/pkg/yunj/app/model"
	"yunj/pkg/yunj/util"

	"github.com/worklz/go-validate"
)

type Postion struct {
	validate.Validator
}

func (v *Postion) HandleDatas(datas map[string]interface{}, scene string) (err error) {
	if scene == "FormSubmit" {
		err = v.HandleDatasByFormSubmit(datas)
		if err != nil {
			return
		}
	}
	return
}

func (v *Postion) HandleDatasByFormSubmit(datas map[string]interface{}) (err error) {
	datas = util.MapFloat64ToUints(datas)
	currTime := time.Now().In(time.Local)
	dbPostion := &model.AdminPostion{
		Name:      util.MapKeyValue(datas, "name", ""),
		Intro:     util.MapKeyValue(datas, "intro", ""),
		UpdatedAt: &currTime,
	}
	// id
	var id uint64
	if idRaw, exists := datas["id"]; exists {
		if idVal, err := util.ToUint64(idRaw); err == nil && idVal > 0 {
			id = idVal
		}
	}
	// code
	code := util.MapKeyValue(datas, "code", "")
	if code != "" {
		// 判断是否存在
		codeExistsQuery := global.MySQL.Model(&model.AdminPostion{}).Where("`code` = ?", code)
		if id > 0 {
			codeExistsQuery.Where("`id` != ?", id)
		}
		var codeExistsCount int64
		if err = codeExistsQuery.Count(&codeExistsCount).Error; err != nil {
			return fmt.Errorf("数据查询异常！%v", err)
		}
		if codeExistsCount > 0 {
			return fmt.Errorf("岗位标识【%s】已存在！", code)
		}
		dbPostion.Code = code
	}
	if id > 0 {
		// 编辑
		dbPostion.Id = id
	} else {
		// 新增
		dbPostion.CreatedAt = &currTime
		dbPostion.State = stateenum.NORMAL
	}
	datas["dbPostion"] = dbPostion
	// role_ids
	roleIds := util.MapKeyValue(datas, "role_ids", []any{})
	dbPostionRoles := []*model.AdminPostionRole{}
	for _, roleIdRaw := range roleIds {
		if roleId, err := util.ToUint64(roleIdRaw); err == nil && roleId > 0 {
			dbPostionRoles = append(dbPostionRoles, &model.AdminPostionRole{
				PostionId: dbPostion.Id,
				RoleId:    roleId,
			})
		}
	}
	datas["dbPostionRoles"] = dbPostionRoles
	return
}
